package com.wyx.SpringSecurityConfig;

import com.wyx.SpringSecurityConfig.mapper.SecurityUserMapper;
import com.wyx.SpringSecurityConfig.pojo.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    SecurityUserMapper securityUserMapper;


    @Autowired
    MyPasswordEncoder myPasswordEncoder;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SecurityUser user = securityUserMapper.getSecurityUserByUserName(username);

        List<String> roleListByUserName = securityUserMapper.getRoleListByUserName(username);

        // 设置权限，通过逗号分割
        StringBuilder role = new StringBuilder();
        for (String s : roleListByUserName) {
            role.append("ROLE_"+s);
            role.append(",");
        }
        //消除最后一个分号
        if (role.length()>=1){
            role.replace(role.length()-1,role.length(),"");
        }else {
            role.append("");
        }

        List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(String.valueOf(role));
        SecurityUser securityUser = new SecurityUser(user.getId(),user.getUsername(),
                user.getPassword(),user.getSalt());

        if (securityUser.getUsername()==null){
            throw  new UsernameNotFoundException("用户名不存在！");
        }

        return new User(securityUser.getUsername(),securityUser.getPassword(),authorityList);

    }
}